<?php

class CompanyController extends Controller
{

    public function actionAdd()
    {
	$userModel = FactoryService::get('user')->get(Yii::app()->user->getId());
	if (Yii::app()->getRequest()->getIsPostRequest()) {
	    $company = Yii::app()->getRequest()->getParam('company');
	    $company = PurifierManager::getInstance()->filter($company);
	    $company['user_id'] = $userModel->getId();
	    $company['register_date'] = date('Y-m-d H:i:s');

	    $errors = false;
	    if (isset($company['id']) && !empty($company['id'])) {
		$companyModel = FactoryService::get('company')->get($company['id']);
		if ($companyModel) {
		    $companyModel->setDbData((object) $company);
		}
	    }else {
		$companyModel = new CompanyModel((object) $company);
	    }
	    if (!$companyModel) {
		throw new Exception('404', 'Error');
	    }
	    if (FactoryService::get('company')->save($companyModel)) {
		$logo = CUploadedFile::getInstanceByName('logo');
		if ($logo) {
		    if ($logo->getSize() > Yii::app()->params['maxUploadSize']) {
			$errors['sizeErr'] = 'Размер файла больше допустимого';
		    }

		    if (!in_array(strtolower($logo->getExtensionName()), Yii::app()->params['allowedTypes'])) {
			$errors['sizeErr'] = 'Недопустимый тип загружаемого файла';
		    }
		    if (!$errors) {
			$path = $userModel->getUploadPath(true) . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR;
			if (!file_exists($path)) {
			    mkdir($path, 0777, true);
			}
			$filename = $companyModel->getId() . '.' . $logo->getExtensionName();
			if ($logo->saveAs($path . $filename)) {
			    $imageInfo = getimagesize($path . $filename);
			    if ($imageInfo[0] > Yii::app()->params['logo']['width'] || $imageInfo[1] > Yii::app()->params['logo']['height']) {
				$file = Yii::app()->image->load($path . $filename);
				$file->resize(Yii::app()->params['logo']['width'], Yii::app()->params['logo']['height'])->save();
			    }
			    $companyModel->logo = implode(DIRECTORY_SEPARATOR, array(
				Yii::app()->params['uploadDirectory'],
				$userModel->getUploadPath(),
				'logo',
				$companyModel->getId() . '.' . $logo->getExtensionName()
				    ));

			    FactoryService::get('company')->save($companyModel);
			}
		    }
		    else {
			Yii::app()->user->setFlash('companyErr', implode('<br />', $errors));
		    }
		}
	    }	    
	    Yii::app()->getRequest()->redirect($this->createUrl('company/view', array('id' => $companyModel->getId(), 'url' => $companyModel->getDbData('url'))));
	}
	$this->breadcrumbs = array(
	    'Компании' => array('/company'),
	    'Добавление / редактирование компании'
	);
	$activityList = FactoryService::get('activity')->getAll();
	$this->render('add', array('model' => new CompanyModel(), 'activities' => $activityList));
    }

    public function actionEdit()
    {
	$id = Yii::app()->getRequest()->getParam('id');
	if (!$id) {
	    throw new CHttpException(404, 'page not found');
	}
	$model = FactoryService::get('company')->get($id);
	if (!$model) {
	    throw new CHttpException(404, 'page not found');
	}
	if ($model->getDbData('user_id') !== Yii::app()->user->getId()) {
	    throw new CHttpException(404, 'page not found');
	}
	$this->breadcrumbs = array(
	    'Компании' => array('company/'),
	    $model->getDbData('title') => array('company/view', 'id' => $model->getId(), 'url' => $model->getDbData('url')),
	    'Редактирование'
	);
	$activityList = FactoryService::get('activity')->getAll();
	$this->render('add', array('model' => $model, 'activities' => $activityList));
    }

    public function actionView()
    {
	$url = Yii::app()->getRequest()->getParam('url');
	$id = Yii::app()->getRequest()->getParam('id');
	if (!$id) {
	    throw new CHttpException(404, 'Тут пусто');
	}
	$model = FactoryService::get('company')->get($id);
	if (!$model) {
	    throw new CHttpException(404, 'Тут пусто');
	}
	FactoryService::get('company')->getExtendedData($model);
	$this->breadcrumbs = array(
	    'Компании' => array('/company'),
	    $model->getDbData('title')
	);

	$this->render('view', array('model' => $model));
    }

    public function actionList()
    {
	$page = Yii::app()->request->getParam('page', 1);
	$order = Yii::app()->request->getParam('order', 'id');
	$pager = new CPagination(FactoryService::get('company')->getCount());
	$pager->setPageSize(Yii::app()->params['perPage']);
	$models = FactoryService::get('company')->getCompanyList(
		array('order' => $order . ' DESC '), $page, Yii::app()->params['perPage']
	);
	$this->breadcrumbs = array(
	    'Компании' => array('/company'),
	    $order == 'id' ? 'Новые' : 'Лучшие' => array('company/list', 'order' => $order)
	);
	$activityList = FactoryService::get('activity')->getAll();	
	$this->render('list', array(
	    'models' => $models,
	    'pager' => $pager,
	    'page' => $page,
	    'activities' => $activityList
	));
    }

    public function actionIndex()
    {	
	$this->breadcrumbs = array(
	    'Компании'
	);
	$activityList = FactoryService::get('activity')->getAll();

	$this->render('index', array(
	    'last' => FactoryService::get('company')->getCompanyList(array('order' => 'id DESC')),
	    'best' => FactoryService::get('company')->getCompanyList(array('order' => 'karma DESC')),
	    'itemCount' => FactoryService::get('company')->getCount(),
	    'activities' => $activityList
	));
    }

}

?>
